A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.
Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.
In [32]:
def bread(test_funct):
def hyderabad():
print("</''''''\>")
test_funct()
print("<\______/>")
return hyderabad
def ingredients(test_funct):
def chennai():
print("#tomatoes#")
test_funct()
print("~salad~")
return chennai
def cheese(food="--Say Cheese--"):
print(food)
In [6]:
ch = bread(test_funct=cheese)
In [7]:
ch()
In [8]:
inn = bread(ingredients(cheese))
inn()
A function decorator is applied to a function definition by placing it on the line before that function definition begins
In [9]:
@bread
@ingredients
def sandwich(food="--Say Cheese--"):
print(food)
sandwich()
!!! Order Matters !!!
In [10]:
@ingredients
@bread
def sandwich(food="--Say Cheese--"):
print(food)
sandwich()
In [10]:
@bread
@ingredients
def hotdog(food="Jam"):
print(food)
hotdog()
In [17]:
def diet_sandwitch(inner_func):
def inner():
print("salad")
return inner
In [28]:
@ingredients
@diet_sandwitch
def sandwich(food="--Say Cheese--"):
print(food)
sandwich()
We can create a function which can take an argument and
In [12]:
def Names(test_funct):
def inner():
print("{Hello}")
print("\tA-Priya")
print("\tManish Gupta")
print("\tNeha", end="\n\t")
test_funct()
print("(/Hello}")
return inner
@Names
def print_AShanti():
print("A-Shanti")
print_AShanti()
In [35]:
In [ ]:
In [ ]:
In [22]:
class A(object):
def method(*argv):
return argv
a = A()
a.method
Out[22]:
In [23]:
a.method('an arg')
Out[23]:
In [24]:
class A(object):
@staticmethod
def method(*argv):
return argv
a = A()
a.method
Out[24]:
When we call a static method we don’t get any additional arguments.
In [25]:
a.method('an arg')
Out[25]:
In [3]:
class A(object):
@classmethod
def method(*argv):
return argv
a = A()
a.method
Out[3]:
In [2]:
a.method('an arg')
Out[2]:
In [3]:
def test(strg):
print("Name: ", strg)
def hello(func, name):
print("Ja")
func(name)
hello(test, "Mayank")
In [4]:
class B(object):
@classmethod
def method(*argv):
return argv
In [5]:
a = B()
a.method()
Out[5]: